package codetop.huawei.T227;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author: 18362
 * @Create: 2022-09-12 11:09:50 星期一
 */
class Solution {
    public int calculate(String s) {
        Deque<Integer> numStack = new LinkedList<>();
        Deque<Character> optStack = new LinkedList<>();
        int i = 0;
        while (i < s.length()) {
            char c = s.charAt(i);
            if (c == ' ') {
                i++;
                continue;
            }
            if (c == '+' || c == '-' || c =='*' || c == '/') {
                optStack.push(c);
                i++;
                continue;
            }
            int num = 0;
            while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                char d = s.charAt(i++);
                if (d < '0' || d > '9')
                    break;
                num = num * 10 + d - '0';
            }
            if (!optStack.isEmpty()) {
                char opt = optStack.peek();
                if (opt == '*' || opt == '/') {
                    optStack.pop();
                    int other = numStack.pop();
                    numStack.push(opt == '*' ? num * other : other / num);
                } else
                    numStack.push(num);
            } else
                numStack.push(num);
        }
        int res = numStack.removeLast();
        while (!numStack.isEmpty()) {
            int num = numStack.removeLast();
            char opt = optStack.removeLast();
            res = opt == '+' ? res + num : res - num;
        }
        return res;
    }
}